#include "symboltable.h"

struct symbol *lookup_by_name (struct symbol *table, char *name)
{
	if (! table)
	{
		return 0;
	}
	else if (! strcmp (name, table->name))
	{
		return table;
	}
	else
	{
		return lookup_by_name (table->next, name);
	}
}

struct symbol *insert (struct symbol *table, char *name, int address, enum section section, enum access access)
{
	struct symbol *node;
	if (! table)
	{
		node = new (name, address, section, access);
		node->next = table;
		return node;
	}
	else if (! strcmp (name, table->name))
	{
		if (table->address < 0)
		{
			table->address = address;
			table->section = section;
		}
		else
		{
			yyerror ("redefinition");
		}
		return table;
	}
	else 
	{
		table->next = insert (table->next, name, address, section, access);
		return table;
	}
}

struct symbol *new (char *name, int address, enum section section, enum access access)
{
	struct symbol *node;
	node = (struct symbol *) malloc (sizeof (struct symbol));
	strcpy (node->name, name);
	node->address = address;
	node->section = section;
	node->access = access;
	node->next = 0;
	return node;
}

void print_table (struct symbol *table)
{
	if (table)
	{
		printf ("%s %x %s %s\n", table->name, table->address, table->section == S_TEXT ? "TEXT": "DATA", table->access == S_GLOBAL ? "GLOBAL" : "LOCAL");
		print_table (table->next);
	}
}

struct symbol *destroy (struct symbol *table)
{
	if (table)
	{
		destroy (table->next);
		free (table);
	}
	return 0;
}

